//
//  HMHomeViewController.m
//  HMMeituanHD
//
//  Created by apple on 2017/5/16.
//  Copyright © 2017年 itheima. All rights reserved.
//

#import "HMHomeViewController.h"
#import "HMHomeNavView.h"

#import "HMCategoryViewController.h"
#import "HMDistrictViewController.h"
#import "HMSortViewController.h"

#import "HMSearchViewController.h"
#import "HMNavigationController.h"
#import "HMCollectViewController.h"
#import "HMMapViewController.h"

#import "HMCategoryModel.h"
#import "HMSortModel.h"



#import "AwesomeMenu.h"


@interface HMHomeViewController ()<AwesomeMenuDelegate, HMRequestParam>

//当前分类
@property (nonatomic, copy) NSString *currentCategory;
//当前区域
@property (nonatomic, copy) NSString *currentDistrict;
//当前排序
@property (nonatomic, strong) NSNumber *currentSort;

//Path菜单
@property (nonatomic, strong) AwesomeMenu *pathMenu;


@end

@implementation HMHomeViewController



@synthesize cities = _cities;



- (void)viewDidLoad {
    [super viewDidLoad];
    
    //设置导航栏
    [self setupNav];
    
    //监听通知
    [HMNoteCenter addObserver:self selector:@selector(cityDidChangeNote:) name:HMCityDidChangeNote object:nil];
    
    [HMNoteCenter addObserver:self selector:@selector(districtDidChangeNote:) name:HMDistrictDidChangeNote object:nil];
    
    [HMNoteCenter addObserver:self selector:@selector(categoryDidChangeNote:) name:HMCategoryDidChangeNote object:nil];
    
    [HMNoteCenter addObserver:self selector:@selector(sortDidChangeNote:) name:HMSortDidChangeNote object:nil];
    
    //监听设备朝向 特点: 应用启动时,会自动调用一次响应方法,无论朝向是否改变
    [HMNoteCenter addObserver:self selector:@selector(orientationDidChangeNote) name:UIDeviceOrientationDidChangeNotification object:nil];
    
    //设置path菜单
    [self setupAwesomeMenu];
    
    //设置默认刷新
    [self.collectionView.mj_header beginRefreshing];

    [HMDataBase new];
}

#pragma mark - HMRequestParam


- (HMRequestType)addCustemParam:(NSMutableDictionary *)baseParam{
 
    //设置分类
    if (self.currentCategory != nil) { //设置了分类
        
        [baseParam setValue:self.currentCategory forKey:@"category"];
    }
    //设置区域
    if (self.currentDistrict != nil) {
        
        [baseParam setValue:self.currentDistrict forKey:@"region"];
    }
    
    //设置排序
    [baseParam setValue:self.currentSort forKey:@"sort"];
    
    return HMRequestTypeNetwork;
}


#pragma mark - AwesomeMenu

//设置path菜单
- (void)setupAwesomeMenu{

    //创建开始Item
    AwesomeMenuItem *startItem = [[AwesomeMenuItem alloc] initWithImage:[UIImage imageNamed:@"icon_pathMenu_background_normal"] highlightedImage:[UIImage imageNamed:@"icon_pathMenu_background_highlighted"] ContentImage:[UIImage imageNamed:@"icon_pathMenu_mainMine_normal"] highlightedContentImage:[UIImage imageNamed:@"icon_pathMenu_mainMine_highlighted"]];
    
    //2. 添加其他几个按钮
    AwesomeMenuItem *item0 = [[AwesomeMenuItem alloc]
                              initWithImage:[UIImage imageNamed:@"bg_pathMenu_black_normal"]
                              highlightedImage:nil
                              ContentImage:[UIImage imageNamed:@"icon_pathMenu_mainMine_normal"]
                              highlightedContentImage:[UIImage imageNamed:@"icon_pathMenu_mainMine_highlighted"]];
    
    AwesomeMenuItem *item1 = [[AwesomeMenuItem alloc]
                              initWithImage:[UIImage imageNamed:@"bg_pathMenu_black_normal"]
                              highlightedImage:nil
                              ContentImage:[UIImage imageNamed:@"icon_pathMenu_collect_normal"]
                              highlightedContentImage:[UIImage imageNamed:@"icon_pathMenu_collect_highlighted"]];
    
    AwesomeMenuItem *item2 = [[AwesomeMenuItem alloc]
                              initWithImage:[UIImage imageNamed:@"bg_pathMenu_black_normal"]
                              highlightedImage:nil
                              ContentImage:[UIImage imageNamed:@"icon_pathMenu_scan_normal"]
                              highlightedContentImage:[UIImage imageNamed:@"icon_pathMenu_scan_highlighted"]];
    
    AwesomeMenuItem *item3 = [[AwesomeMenuItem alloc]
                              initWithImage:[UIImage imageNamed:@"bg_pathMenu_black_normal"]
                              highlightedImage:nil
                              ContentImage:[UIImage imageNamed:@"icon_pathMenu_more_normal"]
                              highlightedContentImage:[UIImage imageNamed:@"icon_pathMenu_more_highlighted"]];
    
    NSArray *items = @[item0, item1, item2, item3];
    
    //创建菜单
    self.pathMenu = [[AwesomeMenu alloc] initWithFrame:CGRectZero startItem:startItem menuItems:items];
    
    //设置菜单按钮展示范围
    self.pathMenu.menuWholeAngle = M_PI_2;
    //设置代理 监听事件
    self.pathMenu.delegate = self;
    //设置透明度
    self.pathMenu.alpha = 0.5;
    //取消开始Item的旋转
    self.pathMenu.rotateAddButton = NO;
    [self.view addSubview:self.pathMenu];
}

//点击菜单Item后调用
- (void)awesomeMenu:(AwesomeMenu *)menu didSelectIndex:(NSInteger)idx{

    switch (idx) {
        case 0:
            HMLog(@"个人信息");
            break;
        case 1:
        {
            HMCollectViewController *collectVc = [[HMCollectViewController alloc] initWithCompletedBlock:^{
                
                menu.startButton.contentImageView.image = [UIImage imageNamed:@"icon_pathMenu_mainMine_normal"];
                menu.startButton.contentImageView.highlightedImage = [UIImage imageNamed:@"icon_pathMenu_mainMine_highlighted"];
                
                //动画改变透明度
                menu.alpha = 0.5f;
            }];
            [self presentViewController:[[HMNavigationController alloc] initWithRootViewController:collectVc] animated:YES completion:nil];
        }
            break;
        case 2:
            HMLog(@"历史记录");
            break;
        case 3:
            HMLog(@"设置");
            break;
            
        default:
            break;
    }
}

//将要动画打开菜单时调用
- (void)awesomeMenuWillAnimateOpen:(AwesomeMenu *)menu{

    menu.startButton.contentImageView.image = [UIImage imageNamed:@"icon_pathMenu_cross_normal"];
    menu.startButton.contentImageView.highlightedImage = [UIImage imageNamed:@"icon_pathMenu_cross_highlighted"];
    
    //动画改变透明度
    [UIView animateWithDuration:0.25 animations:^{
        menu.alpha = 1.f;
    }];
}

//将要动画关闭菜单时调用
- (void)awesomeMenuWillAnimateClose:(AwesomeMenu *)menu{

    menu.startButton.contentImageView.image = [UIImage imageNamed:@"icon_pathMenu_mainMine_normal"];
    menu.startButton.contentImageView.highlightedImage = [UIImage imageNamed:@"icon_pathMenu_mainMine_highlighted"];
    
    //动画改变透明度
    [UIView animateWithDuration:0.25 animations:^{
        menu.alpha = 0.5f;
    }];
}



#pragma mark - 通知相关

//设备朝向变化调用
- (void)orientationDidChangeNote{
    
    //设置开始Item的位置  menu参考视图的高度不是屏幕的高度,内部实现减去了64点(状态栏+导航栏高度)
    CGFloat menuViewHeight = HMRealScreenHeight - 64;
    self.pathMenu.startPoint = CGPointMake(HMAwesomeMenuMargin, menuViewHeight - HMAwesomeMenuMargin);
}

//排序变化调用
- (void)sortDidChangeNote:(NSNotification *)note{

    //获取参数
    HMSortModel *sort = note.userInfo[HMSortDidChangeNoteModelKey];
    //设置导航栏Item
    UIBarButtonItem *item = self.navigationItem.leftBarButtonItems[3];
    HMHomeNavView *sortView = item.customView;
    sortView.subTitle = sort.label;
    
    //记录当前的排序
    self.currentSort = sort.value;
    //执行下拉刷新,请求数据
    [self.collectionView.mj_header beginRefreshing];
}

//分类改变后调用
- (void)categoryDidChangeNote:(NSNotification *)note{

    //获取参数
    HMCategoryModel *category = note.userInfo[HMCategoryDidChangeNoteModelKey];
    NSString *subCategory = note.userInfo[HMCategoryDidChangeNoteSubtitleKey];
    //设置导航栏Item
    UIBarButtonItem *item = self.navigationItem.leftBarButtonItems[1];
    HMHomeNavView *categoryView = item.customView;
    categoryView.title = category.name;
    categoryView.subTitle = [subCategory isEqualToString:@"全部"] ? nil : subCategory;
    
    /**
     *  category参数设置规则: 如果有二级分类,则设置为二级分类;如果没有二级分类,则设置一级分类;没有没有一级分类,则不需要设置分类参数
     
     1> 点击"全部分类:   不传参数 category = nil
     2> 点击一级菜单通知:  传递一级名称
     3> 点击二级-"全部"通知: 传递一级名称
     4> 点击二级菜单通知:  传递二级名称
     
     */
    
    //记录当前的分类
    if ([category.name isEqualToString:@"全部分类"]) { //情况1
        
        self.currentCategory = nil;
        
    } else if ((subCategory == nil) || ([subCategory isEqualToString:@"全部"])) { //情况2 & 情况3
     
        self.currentCategory = category.name;
        
    }else {
    
        self.currentCategory = subCategory;
    }
    
    //执行下拉刷新,请求数据
    [self.collectionView.mj_header beginRefreshing];
}

//区域改变后调用
- (void)districtDidChangeNote:(NSNotification *)note{

    //获取参数
    HMDistrictModel *district = note.userInfo[HMDistrictDidChangeNoteModelKey];
    NSString *subDistrict = note.userInfo[HMDistrictDidChangeNoteSubtitleKey];
    
    //设置导航栏Item
    UIBarButtonItem *item = self.navigationItem.leftBarButtonItems[2];
    HMHomeNavView *districtView = item.customView;
    districtView.title = [NSString stringWithFormat:@"%@-%@", self.currentCityName, district.name];
    districtView.subTitle = [subDistrict isEqualToString:@"全部"] ? nil : subDistrict;
    
    /**
     *  district参数设置规则: 如果有二级区域,则设置为二级区域;如果没有二级区域,则设置一级区域;没有没有一级区域,则不需要设置区域参数
     
     1> 点击"全部":   不传参数 district = nil
     2> 点击一级菜单通知:  传递一级名称
     3> 点击二级-"全部"通知: 传递一级名称
     4> 点击二级菜单通知:  传递二级名称
     
     */
    
    //记录当前的区域
    if ([district.name isEqualToString:@"全部"]) { //情况1
        
        self.currentDistrict = nil;
        
    } else if ((subDistrict == nil) || ([subDistrict isEqualToString:@"全部"])) { //情况2 & 情况3
        
        self.currentDistrict = district.name;
        
    }else {
        
        self.currentDistrict = subDistrict;
    }
    
    //执行下拉刷新,请求数据
    [self.collectionView.mj_header beginRefreshing];
}

//城市改变后调用
- (void)cityDidChangeNote:(NSNotification *)note{

    //获取参数
    NSString *cityName = note.userInfo[HMCityDidChangeNoteCityName];
    //设置导航栏Item
    UIBarButtonItem *item = self.navigationItem.leftBarButtonItems[2];
    HMHomeNavView *districtView = item.customView;
    districtView.title = [NSString stringWithFormat:@"%@-全部", cityName];
    //记录当前城市
    self.currentCityName = cityName;
    //清空子标题
    districtView.subTitle = nil;
    //清空当前记录的区域
    self.currentDistrict = nil;
    //执行下拉刷新,请求数据
    [self.collectionView.mj_header beginRefreshing];
}

#pragma mark - 导航栏相关

//设置导航栏
- (void)setupNav{

    //设置右侧Item item本身不能设置高亮图片,需要包装btn
    UIBarButtonItem *mapItem = [UIBarButtonItem barBuutonItemWithTarget:self action:@selector(clickMapItem) icon:@"icon_map" highlighticon:@"icon_map_highlighted"];
    
    UIBarButtonItem *searchItem = [UIBarButtonItem barBuutonItemWithTarget:self action:@selector(clickSearchItem) icon:@"icon_search" highlighticon:@"icon_search_highlighted"];
    self.navigationItem.rightBarButtonItems = @[mapItem, searchItem];
    
    //设置左侧Item
    UIBarButtonItem *logoItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_meituan_logo"] style:UIBarButtonItemStylePlain target:nil action:NULL];

    
    //禁用item
    logoItem.enabled = NO;
    
    HMHomeNavView *categoryView = [HMHomeNavView homeNavView];
    //设置数据  利用拉伸优先级设置子标题为空时,让标题占满自定义视图的高度
    categoryView.title = @"全部分类";
    categoryView.subTitle = nil;
    categoryView.iconImgName = @"icon_category_-1";
    categoryView.iconHighligtedImgName = @"icon_category_highlighted_-1";
    
    //监听action事件
    [categoryView addTarget:self action:@selector(clickCategoryItem) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *categoryItem = [[UIBarButtonItem alloc] initWithCustomView:categoryView];
    
    HMHomeNavView *districtView = [HMHomeNavView homeNavView];
    //设置数据
    districtView.title = @"北京-全部";
    districtView.subTitle = nil;
    districtView.iconImgName = @"icon_district";
    districtView.iconHighligtedImgName = @"icon_district_highlighted";
    
    //监听action事件
    [districtView addTarget:self action:@selector(clickDistrictItem) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *districtItem = [[UIBarButtonItem alloc] initWithCustomView:districtView];
    
    HMHomeNavView *sortView = [HMHomeNavView homeNavView];
    //设置数据
    sortView.title = @"排序";
    sortView.subTitle = @"默认排序";
    sortView.iconImgName = @"icon_sort";
    sortView.iconHighligtedImgName = @"icon_sort_highlighted";
    //监听action事件
    [sortView addTarget:self action:@selector(clickSortItem) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *sortItem = [[UIBarButtonItem alloc] initWithCustomView:sortView];
    
    self.navigationItem.leftBarButtonItems = @[logoItem, categoryItem, districtItem, sortItem];
}

- (void)clickMapItem{

    HMMapViewController *mapVc = [HMMapViewController new];
    
    [self presentViewController:[[HMNavigationController alloc] initWithRootViewController:mapVc] animated:YES completion:nil];
}

- (void)clickSearchItem{
    
    HMSearchViewController *searchVc = [HMSearchViewController new];
    
    [self presentViewController:[[HMNavigationController alloc] initWithRootViewController:searchVc] animated:YES completion:nil];
}


- (void)clickCategoryItem{
    //创建控制器
    HMCategoryViewController *categoryVc = [HMCategoryViewController new];
    
    //设置modal展示样式
    categoryVc.modalPresentationStyle = UIModalPresentationPopover;
    
    //设置来源视图/barButtonItem
    categoryVc.popoverPresentationController.barButtonItem = self.navigationItem.leftBarButtonItems[1];
    //设置Popover的尺寸
    categoryVc.preferredContentSize = CGSizeMake(categoryVc.popoverView.width, categoryVc.popoverView.height);
    //进行modal展示
    [self presentViewController:categoryVc animated:YES completion:nil];
}

- (void)clickDistrictItem{
    
    //创建控制器
    HMDistrictViewController *districtVc = [HMDistrictViewController new];
    
    //设置modal展示样式
    districtVc.modalPresentationStyle = UIModalPresentationPopover;
    
    //设置来源视图/barButtonItem
    districtVc.popoverPresentationController.barButtonItem = self.navigationItem.leftBarButtonItems[2];
    //设置Popover的尺寸
    districtVc.preferredContentSize = CGSizeMake(districtVc.popoverView.width, CGRectGetMaxY(districtVc.popoverView.frame));

    //遍历所有城市
    for (HMCityModel *city in self.cities) {
        if ([city.name isEqualToString:self.currentCityName]) {
            //传递当前城市的一级区域数据
            districtVc.distrcits = city.districts;
        }
    }
    
    //进行modal展示
    [self presentViewController:districtVc animated:YES completion:nil];
}

- (void)clickSortItem{
    
    HMSortViewController *sortVc = [HMSortViewController new];
    
    //设置modal展示样式
    sortVc.modalPresentationStyle = UIModalPresentationPopover;
    
    //设置来源视图/barButtonItem
    sortVc.popoverPresentationController.barButtonItem = self.navigationItem.leftBarButtonItems[3];
    
    //进行modal展示
    [self presentViewController:sortVc animated:YES completion:nil];
}



#pragma mark - 懒加载

- (NSNumber *)currentSort{

    if (_currentSort == nil) {
        _currentSort = @1;
    }
    return _currentSort;
}

- (NSArray<HMCityModel *> *)cities{

    if (_cities == nil) {
        //获取城市数据
        NSString *path = [[NSBundle mainBundle] pathForResource:@"cities.plist" ofType:nil];
        NSArray *dictArr = [NSArray arrayWithContentsOfFile:path];
        //字典转模型 city中包含的数组属性中元素也需要转为模型,可以利用yymodal的容器型属性来进行转换
        _cities = [NSArray yy_modelArrayWithClass:[HMCityModel class] json:dictArr];
    }
    return _cities;
}



@end
